from flask import Blueprint, request

from Model.models import NursingNews, db
from Utils.APIResponse import APIResponse

nursing_news_blue = Blueprint("nursing_news", __name__)


@nursing_news_blue.route('/news/batch-upload', methods=['POST'])
def batch_upload_news():
    news_items = request.json
    if not news_items:
        return APIResponse.error({'error': 'No news items provided.'})

    new_news = []
    for item in news_items:
        new_item = NursingNews(title=item['title'], content=item['content'],image_url=item['image_url'])
        new_news.append(new_item)

    db.session.add_all(new_news)
    try:
        db.session.commit()
        return APIResponse.success({'message': 'News items uploaded successfully.'})
    except Exception as e:
        db.session.rollback()
        return APIResponse.error({'error': str(e)})


@nursing_news_blue.route('/news/batch-delete', methods=['POST'])
def batch_delete_news():
    news_ids = request.json.get('news_ids')

    if not news_ids:
        return APIResponse.error({'error': 'No news IDs provided.'})

    try:
        NursingNews.query.filter(NursingNews.id.in_(news_ids)).delete(synchronize_session=False)
        db.session.commit()
        return APIResponse.success({'message': 'News items deleted successfully.'})
    except Exception as e:
        db.session.rollback()
        return APIResponse.error({'error': str(e)})


@nursing_news_blue.route('/news/update/<int:news_id>', methods=['PUT'])
def update_news(news_id):
    news_item = NursingNews.query.get(news_id)
    if not news_item:
        return APIResponse.error({'error': 'News item not found.'}, status_code=404)

    data = request.json
    news_item.title = data.get('title', news_item.title)
    news_item.content = data.get('content', news_item.content)

    try:
        db.session.commit()
        return APIResponse.success({'message': 'News item updated successfully.'})
    except Exception as e:
        db.session.rollback()
        return APIResponse.error({'error': str(e)})


@nursing_news_blue.route('/news/list', methods=['GET'])
def list_news():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    paginated_news = NursingNews.query.order_by(NursingNews.created_at.desc()).paginate(page=page, per_page=per_page,
                                                                                        error_out=False)
    news_items = [{'id': item.id, 'title': item.title, 'content': item.content, 'created_at': item.created_at} for item
                  in paginated_news.items]

    return APIResponse.success({
        'news_items': news_items,
        'total': paginated_news.total,
        'pages': paginated_news.pages,
        'current_page': paginated_news.page
    })
